//
//  OrderDetailViewController.m
//  danpin
//
//  Created by chuangjia on 28/10/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "AppDelegate.h"
#import "WebViewController.h"
#import "orderconfig.h"
#import "AlipayHeader.h"
#import "AppDelegate.h"
#import "UserAddressEditViewController.h"
#import "CommentKeyBord.h"
#import "ZToastManager.h"
#import "WKPopCancelView.h"

@interface OrderDetailViewController ()<UITableViewDataSource,UITableViewDelegate,OrderDelegate,CommentKeyBordDelegate,UIAlertViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,strong)NSMutableDictionary *orderDictionary;
@property(nonatomic,strong)NSMutableArray *orderflowArray;
@property(nonatomic,assign)BOOL istariff_fee;
@property(nonatomic,strong)NSMutableDictionary *alipayDictionary;
@end

@implementation OrderDetailViewController
@synthesize tbView=_tbView;
@synthesize sectionArray=_sectionArray;
@synthesize from=_from;
@synthesize out_trade_no=_out_trade_no;
@synthesize orderDictionary=_orderDictionary;
@synthesize istariff_fee=_istariff_fee;
@synthesize alipayDictionary=_alipayDictionary;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle =@"订单详情";
    if (!_sectionArray) {
        _sectionArray =[[NSMutableArray alloc] init];
    }
    _istariff_fee =NO;
    _sectionArray = [NSMutableArray arrayWithObjects:@"orderinfo",@"allowance",@"address",@"goodinfo",@"goodprice",@"logistics",@"timeline",@"guestmessage", nil];
    if (!_orderDictionary) {
        _orderDictionary = [[NSMutableDictionary alloc] init];
    }
    if (!_orderflowArray) {
        _orderflowArray = [[NSMutableArray alloc] init];
    }
    [self initUI];
    [self getOrderDetailInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([self.from isEqualToString:@"trade"]) {
        self.navigationController.enableBackGesture=NO;
    }else{
        self.navigationController.enableBackGesture=YES;
    }
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}
-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton *)sender;
    switch (btn.tag) {
        case 0:
        {
            if ([self.from isEqualToString:@"trade"])
            {
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[WebViewController class]]) {
                        WebViewController *contro =(WebViewController*)controller;
                         self.navigationController.enableBackGesture=YES;
                        [self.navigationController popToViewController:contro animated:YES];
                        break;
                    }
                }
                
            }else{
              
                if (self.navigationController) {
                    if (self.navigationController.viewControllers.count == 1) {
                        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                           self.navigationController.enableBackGesture=YES;
                    } else {
                        [self.navigationController popViewControllerAnimated:YES];
                           self.navigationController.enableBackGesture=YES;
                    }
                } else {
                    [self dismissViewControllerAnimated:YES completion:nil];
                       self.navigationController.enableBackGesture=YES;
                }
            }
            
        }
            break;
        case 1:
            break;
        default:
            break;
    }
}
-(void)dealloc
{
     self.navigationController.enableBackGesture=YES;
    _tbView.tableFooterView =nil;
    self.tbView = nil;
    self.sectionArray=nil;
    self.orderDictionary =nil;
    self.alipayDictionary =nil;
    _istariff_fee=NO;
    [CommentKeyBord commentKeyboard].mDelegate=nil;
    [[CommentKeyBord commentKeyboard].mTextView resignFirstResponder];
    [[CommentKeyBord commentKeyboard].mTextView removeFromSuperview];
    [CommentKeyBord commentKeyboard].mTextView=nil;
}
//====================================================
//
//====================================================
-(void)getOrderDetailInfo
{
    [ZShare showAnimationView:self.view center:CGPointZero];
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:self.out_trade_no forKey:@"id"];

    __weak typeof (self) wSelf = self;
    [OrderApi getShopOrderById:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result];
        [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        [ZShare hiddenAnimationView:wSelf.view];
    }];
}
-(void)parserResultObject:(id)resultObject
{
    [ZShare hiddenAnimationView:self.view];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id data =  [resultObject objectForKey:@"row"];
        if (data && [data isKindOfClass:[NSDictionary class]]){
            _orderDictionary = [NSMutableDictionary dictionaryWithDictionary:data];
            id order_flow = [_orderDictionary objectForKey:@"order_flow"];
            if (order_flow && [order_flow isKindOfClass:[NSArray class]]) {
                [_orderflowArray removeAllObjects];
                _orderflowArray = [NSMutableArray arrayWithArray:order_flow];
                if (_orderflowArray.count==0) {
                    if ([self.sectionArray containsObject:@"timeline"]) {
                         [self.sectionArray removeObject:@"timeline"];
                    }
                    
                }else
                {
                    if (![self.sectionArray containsObject:@"timeline"]) {
                         [self.sectionArray addObject:@"timeline"];
                    }
                }
            }else{
                if ([self.sectionArray containsObject:@"timeline"]) {
                    [self.sectionArray removeObject:@"timeline"];
                }
            }
            id order_tariff = [_orderDictionary objectForKey:@"order_tariff"];
            if (order_tariff==nil) {
                if ([self.sectionArray containsObject:@"allowance"]) {
                     [self.sectionArray removeObject:@"allowance"];
                }
               
            }else{
                if (![self.sectionArray containsObject:@"allowance"]) {
                    if (self.sectionArray.count>1) {
                        [self.sectionArray insertObject:@"allowance" atIndex:1];
                    }
                }
            }
            id guesst =[_orderDictionary objectForKey:@"guest_message"];
            if (guesst && [guesst isKindOfClass:[NSArray class]]) {
                NSArray *arra =(NSArray*)guesst;
                if (arra.count==0) {
                    if ([self.sectionArray containsObject:@"guestmessage"]) {
                        [_sectionArray removeObject:@"guestmessage"];
                    }
                    
                }else
                {
                    if (![self.sectionArray containsObject:@"guestmessage"]) {
                        [self.sectionArray addObject:@"guestmessage"];
                    }
                }
            }else{
                if ([self.sectionArray containsObject:@"guestmessage"]) {
                    [_sectionArray removeObject:@"guestmessage"];
                }
            }
        }
    }
    [self.tbView reloadData];
}
//====================================================
//
//====================================================

-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)) style:UITableViewStyleGrouped];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =UIColorFromRGB(0xf8f8f8);
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    _tbView.tableFooterView = [self footerView];
}
-(UIView*)footerView
{
    UIView *foot =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80)];
    foot.backgroundColor=[UIColor clearColor];
    UIButton *helpbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    helpbtn.frame = CGRectMake((self.view.frame.size.width-100)/2, (80-30)/2, 100, 30);
    helpbtn.backgroundColor = [UIColor clearColor];
    helpbtn.layer.borderColor = [UIColor redColor].CGColor;
    helpbtn.layer.borderWidth = 1;
    helpbtn.titleLabel.font = FONT(12);
    [helpbtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [helpbtn setTitle:@"联系售后" forState:UIControlStateNormal];
    [helpbtn addTarget:self action:@selector(clickHelpEvent) forControlEvents:UIControlEventTouchUpInside];
    [foot addSubview:helpbtn];
    
    return foot;
}
-(void)clickHelpEvent
{
     [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
}
-(void)sendBtnClick:(UITextView *)textViewGet
{
    if (textViewGet.text.length==0) {
        return;
    }
    NSString *out_trade_no = [[NSString stringWithFormat:@"%@",[_orderDictionary objectForKey:@"out_trade_no"]] replaceNullString];
    NSMutableDictionary *dcit =[NSMutableDictionary dictionary];
    [dcit setValue:out_trade_no forKey:@"out_trade_no"];
    [dcit setValue:textViewGet.text forKey:@"question"];
    __weak typeof (self) wSelf = self;
    [OrderApi addGuestMessage:dcit success:^(AFHTTPRequestOperation *operation, id result) {
        NSDictionary *resultDist =(NSDictionary*)result;
//        NSLog(@"%@",resultDist);
        [wSelf getOrderDetailInfo];
        if(resultDist && [resultDist isKindOfClass:[NSDictionary class]])
        {
             [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
        }
      
    } failure:^(NSError *error) {
        
    }];
    
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_sectionArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sectionTitle =[self.sectionArray objectAtIndex:section];
    if ([sectionTitle isEqualToString:@"timeline"])
    {
        return _orderflowArray.count;
    }else if ([sectionTitle isEqualToString:@"guestmessage"])
    {
        id guesst =[_orderDictionary objectForKey:@"guest_message"];
        if (guesst && [guesst isKindOfClass:[NSArray class]]) {
            NSMutableArray *array = (NSMutableArray *)guesst;
            return array.count;
        }
        return 0;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *sectionTitle =[self.sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"orderinfo"])
    {
        return [OrderDetailTradeCell returnCellHeight:_orderDictionary];
    }else  if ([sectionTitle isEqualToString:@"address"])
    {
        return [OrderAddressCell returnCellHeight:_orderDictionary];
    }else  if ([sectionTitle isEqualToString:@"goodinfo"])
    {
        return [OrderDetailInfoCell returnCellHeight:_orderDictionary];
    }else  if ([sectionTitle isEqualToString:@"goodprice"])
    {
        return [OrderDetailPriceCell returnCellHeight:_orderDictionary];
    }else if([sectionTitle isEqualToString:@"allowance"])
    {
        return [OrderDetailAllowanceCell returnCellHeight:_orderDictionary];
    }
    else  if ([sectionTitle isEqualToString:@"logistics"])
    {
        return [OrderDetaillogisticsCell returnCellHeight:_orderDictionary];
      
    }else if ([sectionTitle isEqualToString:@"timeline"])
    {
        if (indexPath.row>=_orderflowArray.count) {
            return 0;
        }
        NSDictionary *dict  = [_orderflowArray objectAtIndex:indexPath.row];
        return [OrderTimeLineCell returnCellHeight:dict];
    }else if ([sectionTitle isEqualToString:@"guestmessage"])
    {
        
        id guesst =[_orderDictionary objectForKey:@"guest_message"];
        if (guesst && [guesst isKindOfClass:[NSArray class]]) {
            NSMutableArray *array = (NSMutableArray *)guesst;
            if (indexPath.row>array.count) {
                return 0;
            }
            NSDictionary *dict =[array objectAtIndex:indexPath.row];
            return [OrderDetailGuestMessageCell returnCellHeight:dict];
        }
        return 0;
    }
    return 0;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  //  UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
     NSString *sectionTitle =[self.sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"orderinfo"])
    {
        OrderDetailTradeCell *cell = (OrderDetailTradeCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderDetailTradeCell"];
        if(cell == nil)
        {
            cell = [[OrderDetailTradeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderDetailTradeCell"];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
        [cell showInfo:_orderDictionary key:@"OrderDetailTradeCell" indexPath:indexPath];
        return cell;
    }else  if ([sectionTitle isEqualToString:@"address"])
    {
        OrderAddressCell *cell = (OrderAddressCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderAddressCell"];
        if(cell == nil)
        {
            cell = [[OrderAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderAddressCell"];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSDictionary *dict = [_orderDictionary objectForKey:@"order_info"];
        if (dict!=nil && [dict isKindOfClass:[NSDictionary class]]) {
            NSDictionary *shop_address = [dict objectForKey:@"shop_address"];
            [cell showInfo:shop_address key:@"OrderDetailAddressCell" indexPath:indexPath];
        }
        return cell;
    }else  if ([sectionTitle isEqualToString:@"goodinfo"])
    {
        OrderDetailInfoCell *cell = (OrderDetailInfoCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderDetailInfoCell"];
        if(cell == nil)
        {
            cell = [[OrderDetailInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderDetailInfoCell"];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        [cell showInfo:_orderDictionary key:@"OrderDetailInfoCell" indexPath:indexPath];
        return cell;
    }else  if ([sectionTitle isEqualToString:@"goodprice"])
    {
        OrderDetailPriceCell *cell = (OrderDetailPriceCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderDetailPriceCell"];
        if(cell == nil)
        {
            cell = [[OrderDetailPriceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderDetailPriceCell"];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
           
        }
        [cell showInfo:_orderDictionary key:@"OrderDetailPriceCell" indexPath:indexPath];
        return cell;
    }else if([sectionTitle isEqualToString:@"allowance"])
    {
        OrderDetailAllowanceCell *cell = (OrderDetailAllowanceCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderDetailAllowanceCell"];
        if(cell == nil)
        {
            cell = [[OrderDetailAllowanceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderDetailAllowanceCell"];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        [cell showInfo:_orderDictionary key:@"OrderDetailAllowanceCell" indexPath:indexPath];
        return cell;
        
    }else if ([sectionTitle isEqualToString:@"logistics"])
    {
        OrderDetaillogisticsCell *cell = (OrderDetaillogisticsCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderDetaillogisticsCell"];
            if(cell == nil)
            {
                cell = [[OrderDetaillogisticsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderDetaillogisticsCell"];
                cell.backgroundColor=[UIColor whiteColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            }
            [cell showInfo:_orderDictionary key:@"OrderDetaillogisticsCell" indexPath:indexPath];
            return cell;
    }else if ([sectionTitle isEqualToString:@"timeline"])
    {
        OrderTimeLineCell *cell = (OrderTimeLineCell*)[tableView  dequeueReusableCellWithIdentifier:@"timeline"];
        if(cell == nil)
        {
            cell = [[OrderTimeLineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"timeline"];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        if (indexPath.row>=_orderflowArray.count) {
            return cell;
        }
        NSString *key =@"0";
        if (indexPath.row==0) {
            key =@"0";
        }else if (indexPath.row ==_orderflowArray.count-1)
        {
            key =@"1";
        }else
        {
            key = @"2";
        }
        NSDictionary *dict  = [_orderflowArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:key indexPath:indexPath];
        return cell;
    }else if ([sectionTitle isEqualToString:@"guestmessage"])
    {
        OrderDetailGuestMessageCell *cell = (OrderDetailGuestMessageCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderDetailGuestMessageCell"];
        if(cell == nil)
        {
            cell = [[OrderDetailGuestMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderDetailGuestMessageCell"];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        id guesst =[_orderDictionary objectForKey:@"guest_message"];
        if (guesst && [guesst isKindOfClass:[NSArray class]]) {
            NSMutableArray *array = (NSMutableArray *)guesst;
            if (indexPath.row>array.count) {
                return cell;
            }
            NSDictionary *dict =[array objectAtIndex:indexPath.row];
            
            [cell showInfo:dict key:@"OrderDetailGuestMessageCell" indexPath:indexPath];
            return cell;
        }
        
        return cell;
    }
   
    return [self getErrorcell:tableView];
}

- (UITableViewCell*)getErrorcell:(UITableView*)tableView
{
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"ErrorEmptyCell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ErrorEmptyCell"];
    }
    return  cell;
}

-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_help:
        {
            if (obj && [obj isKindOfClass:[NSDictionary class]]) {
                self.istariff_fee = NO;
                NSMutableDictionary *pdict = [NSMutableDictionary dictionary];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[obj objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[obj objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
                NSDictionary *goods_info =[obj objectForKey:@"goods_info"];
                NSString *productDescription =[[NSString stringWithFormat:@"%@",[goods_info objectForKey:@"good_intro"]] replaceNullString];
                if (productDescription.length==0) {
                    productDescription =[[NSString stringWithFormat:@"%@",[obj objectForKey:@"subject"]] replaceNullString];
                }
                [pdict setValue:productDescription forKey:@"body"];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[obj objectForKey:@"total_fee"]] replaceNullString] forKey:@"total_fee"];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[obj objectForKey:@"add_time"]] replaceNullString] forKey:@"add_time"];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[obj objectForKey:@"encryption"]] replaceNullString] forKey:@"encryption"];
            
                if ([self isZhiFu:pdict]) {
                    [self alipay:pdict];
                }
            }
            
        }
            break;
        case BEventType_cancelOrder:
        {
            __block WKPopCancelView *popView=nil;
            popView=[WKPopCancelView showAlertViewWithTitle:@"" subTitle:@"" callBlock:^(WindowClick buttonIndex ,id obj) {
                switch (buttonIndex) {
                    case 0:
                    {
                        popView.hidden=YES;
                        popView=nil;
                    }
                        break;
                    case 1:
                    {
                        if ([self isLogin]) {
                            NSString *objstr =(NSString *)obj;
                            NSString *out_trade_no =[[NSString stringWithFormat:@"%@",[_orderDictionary objectForKey:@"out_trade_no"]] replaceNullString];
                            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                            [dict setValue:out_trade_no forKey:@"out_trade_no"];
                            [dict setValue:objstr forKey:@"reason"];
                            [[ZToastManager ShardInstance] showprogress];
                            __weak typeof (self) wSelf = self;
                            [OrderApi removeOrder:dict success:^(AFHTTPRequestOperation *operation, id result) {
                                [[ZToastManager ShardInstance] hideprogress];
                                if (result&&[result isKindOfClass:[NSDictionary class]]) {
                                    NSDictionary *resultDist =(NSDictionary*)result;
                                    //                        NSLog(@"%@",resultDist);
                                    int code =[[resultDist objectForKey:@"code"] intValue];
                                    [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                                    if (code==1) {
                                        //更新订单列表里面支付状态
                                        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateZhifuStatu" object:nil];
                                        [wSelf.navigationController popViewControllerAnimated:YES];
                                    }
                                }
                                popView.hidden=YES;
                                popView=nil;
                                
                            } failure:^(NSError *error) {
                                
                                popView.hidden=YES;
                                popView=nil;
                                [[ZToastManager ShardInstance] hideprogress];
                            }];
                        }
                        
                    }
                        break;
                    default:
                        break;
                }
            }];
        
        }
            break;
        case BEventType_tariff:
        {
            
            if (_orderDictionary) {
                NSDictionary *order_tariff =[_orderDictionary objectForKey:@"order_tariff"];
                int status = [[order_tariff objectForKey:@"status"] intValue];
                if (status==1) {
                    return;
                }
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
                [dict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
                [dict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"body"]] replaceNullString] forKey:@"body"];
                [dict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"tariff_fee"]] replaceNullString] forKey:@"total_fee"];
                [dict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"add_time"]] replaceNullString] forKey:@"add_time"];
                [dict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"encryption"]] replaceNullString] forKey:@"encryption"];
                
                self.istariff_fee = YES;
                if ([self isZhiFu:dict])
                {
                    __weak typeof (self) wSelf = self;
                    [OrderApi getUserBalance:nil success:^(AFHTTPRequestOperation *operation, id result) {
                        if (result&&[result isKindOfClass:[NSDictionary class]]) {
                            NSDictionary *resultDist =(NSDictionary*)result;
                            if (resultDist && [resultDist isKindOfClass:[NSDictionary class]]) {
                                NSString *balance =[[NSString stringWithFormat:@"%@",[resultDist objectForKey:@"balance"]] replaceNullString];
                                [wSelf usebalanceWithDict:dict balance:balance];
                            }
                        }
                    } failure:^(NSError *error) {
                        [wSelf alipay:dict];
                    }];
                }
                
              
            }
          
        }
            break;
        case BEventType_link:
        {
            OrderTaxViewController *tax = [[OrderTaxViewController alloc] init];
            tax.titleStr =@"帮助";
            tax.urlStr = key;
            [self.navigationController pushViewController:tax animated:YES];
            return;
        }
            break;
        case BEventType_card:
        {
            NSDictionary *dict = [_orderDictionary objectForKey:@"order_info"];
            NSDictionary *shop_address = [dict objectForKey:@"shop_address"];
            UserAddressEditViewController *edit = [[UserAddressEditViewController alloc] init];
            edit.type=1;
            edit.addressDictionary = (NSMutableDictionary*)shop_address;
            [self.navigationController pushViewController:edit animated:YES];
            edit=nil;
        }
            break;
        default:
            break;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *sectionTitle =[self.sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"goodinfo"])
    {
        NSDictionary *goods_info =[_orderDictionary objectForKey:@"goods_info"];
        NSString *urls =[goods_info objectForKey:@"goods_url"];
        WebViewController *web = [[WebViewController alloc] init];
        web.titlestr=@"orderdetail";
        web.urlstr = urls;
        [self.navigationController pushViewController:web animated:YES];
    }
}

//余额补税
-(void)usebalanceWithDict:(NSDictionary*)dict balance:(NSString*)balance
{
    NSString *tempBalance = balance;
    if (tempBalance==nil|| tempBalance.length==0 || [balance floatValue]<=0) {
        [self alipay:dict];
    }else
    {
        self.alipayDictionary =[NSMutableDictionary dictionaryWithDictionary:dict];
        NSString *tem = [NSString stringWithFormat:@"您有可用余额%@，是否使用余额？",tempBalance];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:tem delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"使用余额", nil];
        [alert show];
        alert=nil;
    }
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self alipay:self.alipayDictionary];
        }
            break;
        case 1: //使用
        {
            __weak typeof (self) wSelf = self;
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:[[NSString stringWithFormat:@"%@",[self.alipayDictionary objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
            [OrderApi balanceTariff:dict success:^(AFHTTPRequestOperation *operation, id result) {
                if (result&&[result isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *resultDist =(NSDictionary*)result;
                    int code = [[resultDist objectForKey:@"code"] intValue];
                    if (code==1) {
                        [wSelf getOrderDetailInfo];
                        //更新订单列表里面支付状态
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateZhifuStatu" object:nil];
                    }else
                    {
                        if (resultDist && [resultDist isKindOfClass:[NSDictionary class]]) {
                            id tariff = [resultDist objectForKey:@"tariff"];
                            if (tariff && [tariff isKindOfClass:[NSDictionary class]]) {
                                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"body"]] replaceNullString] forKey:@"body"];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"tariff_fee"]] replaceNullString] forKey:@"total_fee"];
                                [wSelf alipay:dict];
                            }
                        }
                    }
                }
            } failure:^(NSError *error) {
                [wSelf alipay:wSelf.alipayDictionary];
            }];
        }
            break;
        default:
            break;
    }
}

//=================================================
// 订单提交成功判断支付信息
//返回值 json
//{
//    'code' => 1,
//    'msg' => '订单保存成功',
//    'add_time' => $add_time,
//    'total_fee' => $total_fee,
//    'out_trade_no' => $param['out_trade_no'],
//    'encryption' => md5($param['out_trade_no'] . $_SESSION['user_id'] . $total_fee . $Keys . $add_time),
//    'md5str' => $param['out_trade_no'] . $_SESSION['user_id'] . $total_fee . $Keys . $add_time,
//}
// key @"chrdwHDHXT12345ssdlh";
//=================================================
-(BOOL)isZhiFu:(NSDictionary*)dictionary
{
    if (dictionary==nil || ![[dictionary allKeys] containsObject:@"out_trade_no"]) {
        return NO;
    }
    //添加订单后支付
    NSString *add_time =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"add_time"]] replaceNullString];
    NSString *total_fee =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"total_fee"]] replaceNullString];
    NSString *out_trade_no =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"out_trade_no"]] replaceNullString];
    NSString *encryption =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"encryption"]] replaceNullString];
    NSString *md5str = [NSString stringWithFormat:@"%@%@%@chrdwHDHXT12345ssdlh%@",out_trade_no,[ZShare sharedInstance].getUserId,total_fee,add_time];
    md5str = [ZShare md5:md5str];
    if ([md5str isEqualToString:encryption]) {
        return YES;
    }
    return NO;
}

-(void)alipay:(NSDictionary*)dict
{
    NSString *totalfee =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"total_fee"]] replaceNullString];
    if ([totalfee floatValue]==0) {
        return;
    }
    NSString *tradeNO = [dict objectForKey:@"out_trade_no"]; //订单ID（由商家自行制定）
    NSString *productName = [dict objectForKey:@"subject"]; //商品标题
    NSString *productDescription =[dict objectForKey:@"body"];
    NSString *amount = [dict objectForKey:@"total_fee"];; //商品价格
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=self;
     __weak typeof (self) wSelf = self;
    [AlipayRequestConfig alipayWithTradeNO:tradeNO productName:productName productDescription:productDescription amount:amount callback:^(NSDictionary *resultDic) {
        [wSelf orderPayOK:resultDic];
    }];
}
-(void)orderPayOK:(id)info
{
    NSDictionary *resultDic =(NSDictionary *)info;
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=nil;
    NSString *memo = [resultDic objectForKey:@"memo"];
    if (memo.length>0) {
        [[ZToastManager ShardInstance] showtoast:memo];
    }
    
    NSString *resultStatus = [resultDic objectForKey:@"resultStatus"];
    if ([resultStatus isEqualToString:@"9000"]) {
        NSMutableDictionary *dcit =[NSMutableDictionary dictionary];
        [dcit setValue:@"0" forKey:@"rmb"];
        if (self.istariff_fee) {
            NSDictionary *order_tariff =[_orderDictionary objectForKey:@"order_tariff"];
            [dcit setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"tariff_fee"]] replaceNullString] forKey:@"tariff_fee"];
        }
        [dcit setValue:[ZShare DataTOjsonString:resultDic] forKey:@"return_data"];
        [OrderApi alipayReturnUrl:dcit success:^(AFHTTPRequestOperation *operation, id result) {
//            NSLog(@"%@",result);
        } failure:^(NSError *error) {
            
        }];
        
         [self getOrderDetailInfo];
        //更新订单列表里面支付状态
         [[NSNotificationCenter defaultCenter] postNotificationName:@"updateZhifuStatu" object:nil];
    }else  if ([resultStatus isEqualToString:@"6001"])
    {
      
    }
}

@end
